//
//  JokeViewController.m
//  噗嗤
//
//  Created by 火火火火火 on 16/8/16.
//  Copyright © 2016年 cjp. All rights reserved.
//

#import "JokeViewController.h"
#import "JokeTableViewCell.h"
#import <AFNetworking.h>
#import "JokeModel.h"
#import <MJRefresh.h>
#import <MJExtension.h>

@interface JokeViewController ()<UITableViewDelegate , UITableViewDataSource>

@property (strong , nonatomic) UITableView * tableview;
@property (strong , nonatomic) NSMutableArray * dataArr;
@property (strong , nonatomic) JokeModel * jokeModel;

/** 上一次的请求参数 */
@property(nonatomic,strong)NSDictionary *params;

@end

@implementation JokeViewController


- (NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableview = [[UITableView alloc] initWithFrame:self.view.frame style:(UITableViewStylePlain)];
    [self.view addSubview:self.tableview];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    
//    注册cell
    [self.tableview registerNib:[UINib nibWithNibName:@"JokeTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
//    [self setupRefresh];
    [self parse];
}

- (void)parse
{
    NSURL * url  = [NSURL URLWithString:LeeJokeURL];
    NSURLSession * session = [NSURLSession sharedSession];
    
    NSURLSessionTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"请求失败 , %@" , error);
        }else{
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            
            for (NSDictionary * dict in dic[@"items"]) {
                JokeModel * joke = [JokeModel new];
                [joke setValuesForKeysWithDictionary:dict];
                [self.dataArr addObject:joke];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableview reloadData];
            });
        }
    }];
    
    [task resume];
}


//#pragma mark ------- 添加刷新控件 ------------
//- (void)setupRefresh{
//    
//    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewJoke)];
//    // 自动改变透明度
//    self.tableview.mj_header.automaticallyChangeAlpha = YES;
//    [self.tableview.mj_header beginRefreshing];
//    
//    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreJoke)];
//    
//    
//}
//
//#pragma mark ------- 上拉刷新 -------------
//- (void)loadNewJoke{
//    
//    // 结束下拉
//    [self.tableview.mj_footer endRefreshing];
//    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    
//    self.params = params;
//    
//    [[AFHTTPSessionManager manager]GET:LeeJokeURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
//        
//        if (self.params != params) return ;
//        
//        self.dataArr = [JokeModel mj_objectArrayWithKeyValuesArray:responseObject[@"items"]];
//        
//        NSLog(@"%@" , self.dataArr);
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.tableview reloadData];
//            // 结束刷新
//            [self.tableview.mj_header endRefreshing];
//            
//        });
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        if (self.params != params) return ;
//        // 结束刷新
//        [self.tableview.mj_header endRefreshing];
//    }];
//}
//
//#pragma mark ------- 下拉加载 ----------
//- (void)loadMoreJoke{
//    
//    // 结束上拉
//    [self.tableview.mj_header endRefreshing];
//    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    
//    params[@"timestamp"] = self.timestamp;
//    self.params = params;
//    
//    NSString *str = [LeeJokeURL stringByAppendingFormat:@"%zd" , self.params];
//    
//    [[AFHTTPSessionManager manager]GET:str parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
//        
//        if (self.params != params) return ;
//        
//        // 存储timestamp
//        self.timestamp = responseObject[@"timestamp"];
//        
//        NSArray *newMovie = [JokeModel mj_objectArrayWithKeyValuesArray:responseObject[@"videos"]];
//        [self.dataArr addObjectsFromArray:newMovie];
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//            [self.tableview reloadData];
//            // 结束刷新
//            [self.tableview.mj_footer endRefreshing];
//            
//        });
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        if (self.params != params) return ;
//        // 结束刷新
//        [self.tableview.mj_footer endRefreshing];
//        
//    }];
//}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JokeModel *model = self.dataArr[indexPath.row];
    
    return model.cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JokeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    JokeModel  * joke = self.dataArr[indexPath.row];
    
    cell.contentLabel.text = joke.wbody;
    
//    时间格式转化
    NSTimeInterval second = joke.update_time.longLongValue;
    NSDate * date  = [NSDate dateWithTimeIntervalSince1970:second];
    NSDateFormatter * format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"MM-dd HH:mm";
    cell.dateLabel.text = [format stringFromDate:date];
    
    [cell.praiseBtn setTitle:[NSString stringWithFormat:@"%ld" , joke.likes] forState:(UIControlStateNormal)];
    [cell.commentBtn setTitle:[NSString stringWithFormat:@"%ld" , joke.comments] forState:(UIControlStateNormal)];
    
    return cell;
}
//点击点赞按钮
- (IBAction)praiseAC:(UIButton *)sender {
}

//点击收藏按钮
- (IBAction)collectAc:(UIButton *)sender {
    NSLog(@"========");
}

//点击分享按钮
- (IBAction)shareAC:(UIButton *)sender {
}

//点击评论按钮
- (IBAction)commentAC:(UIButton *)sender {
}

@end
